package com.yd.app.mapper;

import com.yd.app.mapper.provider.CouponProvider;
import com.yd.domain.business.Coupon;
import com.yd.domain.business.UserCoupon;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 优惠券Mapper
 * Created by sunxianhui on 2018/3/9.
 */
@Repository
public interface CouponMapper {

    /**
     * 添加优惠券
     * @param coupon
     */
    @Insert("insert into business_coupon  (id,title,des,createTime,number,typeCode,endDate,startDate,dealPrice,discountPrice,discountRatio) values  (#{coupon.id},#{coupon.title},#{coupon.des},#{coupon.createTime},#{coupon.number},#{coupon.typeCode},#{coupon.endDate},#{coupon.startDate},#{coupon.dealPrice},#{coupon.discountPrice},#{coupon.discountRatio})")
    int addCoupon(@Param("coupon") Coupon coupon);

    /**
     * 修改
     * @param coupon
     */
    @Update("update business_coupon set id=#{coupon.id},title=#{coupon.title},des=#{coupon.des},createTime=#{coupon.createTime},number=#{coupon.number},typeCode=#{coupon.typeCode},endDate=#{coupon.endDate},startDate=#{coupon.startDate},dealPrice=#{coupon.dealPrice},discountPrice=#{coupon.discountPrice},discountRatio=#{coupon.discountRatio} where id=#{coupon.id}")
    int updateCoupon(@Param("coupon") Coupon coupon);

    /**
     * 删除
     * @param id
     */
    @Delete("delete from business_coupon where id=#{id}")
    int deleteCouponById(@Param("id") String id);

    /**
     * 根据条件分页查询
     * @param coupon
     * @param startRow
     * @param pageSize
     * @return
     */
    @SelectProvider(method = "searchCouponList", type = CouponProvider.class)
    List<Coupon> getCouponList(@Param("coupon") Coupon coupon, @Param("startRow") int startRow, @Param("pageSize") int pageSize);

    /**
     * 根据条件查询数量
     * @param coupon
     * @return
     */
    @SelectProvider(method = "searchCouponCount", type = CouponProvider.class)
    int getCouponCount(@Param("coupon") Coupon coupon);

    //获取优惠券信息
    @Select("select * from  business_coupon where  id=#{id} and endDate>unix_timestamp(current_timestamp(3))*1000  ")
    Coupon getCouponById(@Param("id") String id);

    /**
     * @return
     */
    @Select("select uc.* from business_user_coupon uc where userId=#{userId}")
    @Results({
            @Result(id = true,property = "couponId" ,column = "couponId"),
            @Result(id = true,property ="coupon",column = "couponId",one =@One(select ="com.yd.app.mapper.CouponMapper.getCouponById"))})
    List<UserCoupon> getUserCouponList(@Param("userId") String userId);

    /**
     * 发放优惠券
     * @param userId
     * @param couponId
     * @param number
     */
    @Insert("insert into business_user_coupon (userId,couponId,number) values (#{userId},#{couponId},#{number}) ON DUPLICATE KEY UPDATE `number`=number+values(number) ")
    void addUserCoupon(@Param("userId") String userId,@Param("couponId") String couponId,@Param("number") int number);
}
